#include "Defect_Sector.h"
#include "qdebug"
Defect_Sector::Defect_Sector()
{

}
int Defect_Sector::D_Sector(HObject Img,HTuple ModelID, HObject &OutImg)
{

    HObject  Region, ConnectedRegions;
    HObject  SelectedRegions,ModelContours, RegionDilation, RegionComplement;
    HObject  ImageResult, ContoursAffineTrans;
    HObject  SelectedContours, Region1, Region3, RegionFillUp;
    HObject  RegionDifference1, RegionErosion1, ConnectedRegions1;
    HObject  SelectedRegions1, RegionErosion, ImageReduced;
    HObject  Region2, ConnectedRegions2, SelectedRegions2;
    HObject  RegionTrans1, RegionTrans2, RegionUnion;
    HObject  RegionTrans, RegionDilation1, RegionDifference;
    HObject  ImageResult1, ImageResult2, ImageResult3;
    HObject  MultiChannelImage, Region4, ConnectedRegions3, SelectedRegions3,Rect;


    HTuple  para, Number2,Number3;
    HTuple  Number1, Row, Column, Angle;
    HTuple  Score, HomMat2DIdentity, HomMat2D, Number,Mean, Deviation;
    HTuple  area1, row1, col1;
	HTuple  area2, row2, col2, S1, S2, AreaC, RowC, ColumnC, HomMat2DIdentityC, HomMat2DScaleC;

    HObject RegionErosion_E, ImageReduced_E, Region_E, ImageEquHisto, ConnectedRegions_E, SelectedRegions_E, BlackReduce;


    SelectedRegions1.Clear();
    SelectedRegions2.Clear();
    SelectedRegions3.Clear();
    para[0] =  m_part.para1;
    para[1] =  m_part.para2;
    para[2] =  m_part.para3;
    para[3] =  m_part.para4;
    para[4] =  m_part.para5;
    para[5] =  m_part.para6;
    para[6] =  m_part.para7;
    para[7] =  m_part.para8;

    int flag = 0;

    try
    {
        OutImg=Img;
        Number2 = 0;
        Number1 = 0;
        GenRectangle1(&Rect, m_part2.x1, m_part2.y1, m_part2.x2, m_part2.y2);
        ReduceDomain(Img, Rect, &Region);

        ModelContours.Clear();
        Threshold(Region, &Region, 0, HTuple(para[0]));
        Connection(Region, &ConnectedRegions);
        SelectShapeStd(ConnectedRegions, &SelectedRegions, "max_area", 70);
		FillUp(SelectedRegions, &SelectedRegions);
        DilationRectangle1(SelectedRegions, &RegionDilation, 15, 15);
        Complement(RegionDilation, &RegionComplement);
        PaintRegion(RegionComplement, Img, &ImageResult, 255, "fill");
        GetShapeModelContours(&ModelContours, ModelID, 1);
        //        GetDeformableModelContours(&ModelContours, ModelID, 1);
        //        HomMat2dIdentity (&HomMat2DIdentity);
        //        HomMat2dScale (HomMat2DIdentity, 0.5, 0.5, 0, 0, &HomMat2DIdentity);
        //        AffineTransContourXld (ModelContours, &ModelContours, HomMat2DIdentity);
        FindShapeModel(ImageResult, ModelID, HTuple(0).TupleRad(), HTuple(360).TupleRad(),
                       HTuple(para[1]), 0, 0.5, "least_squares", (HTuple(4).Append(1)), 0.75,
                &Row, &Column, &Angle, &Score);
        //        FindPlanarUncalibDeformableModel(ImageResult, ModelID, HTuple(0).TupleRad(), HTuple(360).TupleRad(),
        //                                         1, 1, 1, 1, 0.5, 0, 0.5, 0, 0.75, "subpixel", "least_squares", &HomMat2D,
        //                                         &Score);
        if (0 != (Score>HTuple(para[1])))
        {
            HomMat2dIdentity(&HomMat2DIdentity);
            VectorAngleToRigid(0, 0, 0, Row, Column, Angle, &HomMat2D);
            AffineTransContourXld(ModelContours, &ContoursAffineTrans, HomMat2D);
            //            ProjectiveTransContourXld(ModelContours, &ContoursAffineTrans, HomMat2D);


            UnionAdjacentContoursXld(ContoursAffineTrans, &ContoursAffineTrans, 10,
                                     1, "attr_keep");
            SelectContoursXld(ContoursAffineTrans, &SelectedContours, "contour_length",
                              30, 3000, -0.5, 0.5);

            GenRegionContourXld(SelectedContours, &Region1, "filled");
            Union1(Region1, &Region1);

            if (Outer)
            {
                Threshold(ImageResult, &Region3, 0, HTuple(para[2]));
                FillUp(Region3, &RegionFillUp);


                Difference(Region1, RegionFillUp, &RegionDifference1);
				ErosionCircle(RegionDifference1, &RegionErosion1, HTuple(para[3]));
              /*  ErosionRectangle1(RegionDifference1, &RegionErosion1, HTuple(para[3]),
                        HTuple(para[3]));*/
                Connection(RegionErosion1, &ConnectedRegions1);

                SelectShape(ConnectedRegions1, &SelectedRegions1, ((HTuple("area").Append("height")).Append("width")),
                            "and", HTuple(para[4]).TupleConcat((HTuple(3).Append(3))), ((HTuple(99999).Append(500)).Append(500)));
            }
            



            if (Inner)
            {
				AreaCenter(SelectedRegions, &AreaC, &RowC, &ColumnC);
				HomMat2dIdentity(&HomMat2DIdentityC);
                HomMat2dScale(HomMat2DIdentityC, HTuple(para[5]), HTuple(para[5]), RowC, ColumnC, &HomMat2DScaleC);
				AffineTransRegion(SelectedRegions, &RegionErosion, HomMat2DScaleC, "nearest_neighbor");
				

                //ErosionCircle (SelectedRegions, &RegionErosion, HTuple(para[5]));
                ReduceDomain(Img, RegionErosion, &ImageReduced);

				Intensity(RegionErosion, ImageReduced, &Mean, &Deviation);
                Threshold (ImageReduced, &Region2, (Mean+Deviation+HTuple(para[6])), 255);

                Connection(Region2, &ConnectedRegions2);

				/*SelectShape(ConnectedRegions2, &ConnectedRegions2, (HTuple("area").Append("height").Append("width")), "and", HTuple(para[7]).TupleConcat((HTuple(200).Append(200))), 
					(HTuple(99999)).TupleConcat((HTuple(100).Append(100))));*/
				
				SelectShape(ConnectedRegions2, &ConnectedRegions2, ((HTuple("area").Append("height")).Append("width")),
					"and", HTuple(para[7]).TupleConcat((HTuple(2).Append(2))), ((HTuple(99999).Append(2000)).Append(2000)));
				Union1(ConnectedRegions2, &ConnectedRegions2);
				CountObj(ConnectedRegions2, &Number);
				if (Number.D()!=0)
				{
					int a = 111;
				}

			


               
			/*	EquHistoImage(ImageReduced, &ImageEquHisto);
                Threshold(ImageEquHisto, &Region_E, 220, 255);
                Connection(Region_E, &ConnectedRegions_E);
                SelectShape(ConnectedRegions_E, &SelectedRegions_E, ((HTuple("area").Append("height")).Append("width")),
                            "or", HTuple(1200).TupleConcat((HTuple(200).Append(200))), ((HTuple(99999).Append(300)).Append(300)));
				Union1(SelectedRegions_E, &SelectedRegions_E);
*/


                Threshold(ImageReduced, &BlackReduce, 0,(Mean - Deviation -10));
                Connection(BlackReduce, &BlackReduce);
				SelectShape(BlackReduce, &BlackReduce, "area", "and", 400, 99999);
                Union1(BlackReduce, &BlackReduce);
				CountObj(BlackReduce, &Number);
				if (Number != 0)
				{
					int a = 123123;
				}

                
				/*Union2(ConnectedRegions2, SelectedRegions_E, &SelectedRegions2);
				Union2(BlackReduce, SelectedRegions2, &SelectedRegions2);*/
				Union2(BlackReduce, ConnectedRegions2, &SelectedRegions2);
				CountObj(SelectedRegions2, &Number);
				if (Number != 0)
				{
					int a = 0;
				}
                /*
                Threshold(ImageReduced, &Region4, HTuple(0), 20);
                Connection(Region4, &ConnectedRegions3);

                SelectShape(ConnectedRegions3, &SelectedRegions3, ((HTuple("area").Append("height")).Append("width")),
                    "and", HTuple(para[7]).TupleConcat((HTuple(3).Append(3))), ((HTuple(99999).Append(200)).Append(200)));
                    */
            }

            if (Outer&&!Inner)
            {
                Union1(SelectedRegions1, &RegionUnion);
                AreaCenter(SelectedRegions1, &area1, &row1, &col1);
                CountObj(SelectedRegions1, &S1);
                if (S1.D() != 0)
                {
                    TupleConcat(area1[0], 0, &AreaValue);
                }
                else
                {
                    TupleConcat(0, 0, &AreaValue);
                }

                TupleConcat(area1[0],0,&AreaValue);
                CountObj(RegionUnion, &Number);
            }
            else if (!Outer&&Inner)
            {

                Union1(SelectedRegions2, &RegionUnion);
                AreaCenter(SelectedRegions2, &area2, &row2, &col2);
                CountObj(SelectedRegions2, &S2);

                if (S2.D() != 0)
                {
                    TupleConcat(0, area2[0], &AreaValue);
                }
                else
                {
                    TupleConcat(0, 0, &AreaValue);
                }
                CountObj(RegionUnion, &Number);

            }
            else if (Outer&&Inner)
            {

                Union2(SelectedRegions1, SelectedRegions2, &RegionUnion);
                AreaCenter(SelectedRegions1, &area1, &row1, &col1);
                AreaCenter(SelectedRegions2, &area2, &row2, &col2);
                CountObj(SelectedRegions1, &S1);
                CountObj(SelectedRegions2, &S2);
                if (S1.D() != 0 && S2.D() != 0)
                {
                    TupleConcat(area1[0], area2[0], &AreaValue);
                }
                else if (S1.D() == 0 && S2.D() != 0)
                {
                    TupleConcat(0, area2[0], &AreaValue);
                }
                else if (S1.D() != 0 && S2.D() == 0)

                {
                    TupleConcat(area1[0], 0, &AreaValue);
                }
                else
                {
                    TupleConcat(0, 0, &AreaValue);
                }
                CountObj(RegionUnion, &Number);

            }
            else
            {
                TupleConcat(0, 0, &AreaValue);
                Number = 0;
            }




            if (0 != (Number > 0))
            {
                Connection(RegionUnion, &RegionUnion);
                ShapeTrans(RegionUnion, &RegionTrans, "outer_circle");
                DilationCircle(RegionTrans, &RegionDilation1, 3.5);
                Difference(RegionDilation1, RegionTrans, &RegionDifference);
                PaintRegion(RegionDifference, Img, &ImageResult1, 255, "fill");
                PaintRegion(RegionDifference, Img, &ImageResult2, 0, "fill");
                PaintRegion(RegionDifference, Img, &ImageResult3, 0, "fill");
                Compose3(ImageResult1, ImageResult2, ImageResult3, &MultiChannelImage);
                flag = 1;
                OutImg = MultiChannelImage;
            }


            double x = AreaValue[0].D();


            return flag;
        }
		else
		{
			AreaValue.Append(0).Append(0);
			return 2;
		}
    }
    catch(HException ex)
    {
        AreaValue.Append(0).Append(0);
        return 2;
    }
}
